import { Customer, Admin, Room, Booking, LoginRequest, ApiResponse, LoginResponse } from '@/types';

// 基础 API URL - 修改为相对路径
const API_BASE_URL = '/api';

// 通用请求函数
async function request<T>(
  url: string, 
  options?: RequestInit
): Promise<ApiResponse<T>> {
  try {
    // 获取JWT token
    const token = localStorage.getItem('token');
    
    console.log('发送请求:', `${API_BASE_URL}${url}`);
    console.log('请求选项:', JSON.stringify(options, null, 2));
    
    // 构建请求头
    const headers: HeadersInit = {
      'Content-Type': 'application/json',
    };

    // 如果是登录请求，不添加 Authorization 头
    if (!url.includes('/login')) {
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      } else {
        console.warn('非登录请求缺少 token');
      }
    }

    const response = await fetch(`${API_BASE_URL}${url}`, {
      ...options,
      headers: {
        ...headers,
        ...options?.headers,
      },
    });

    console.log('收到响应:', response.status, response.statusText);

    if (!response.ok) {
      if (response.status === 401) {
        // token过期或无效，清除token
        localStorage.removeItem('token');
        localStorage.removeItem('userType');
        // 触发未授权事件
        window.dispatchEvent(new Event('unauthorized'));
        throw new Error('登录已过期，请重新登录');
      }
      
      // 尝试解析错误响应
      const errorText = await response.text();
      let errorData;
      try {
        errorData = JSON.parse(errorText);
      } catch (e) {
        errorData = { message: errorText };
      }
      
      throw new Error(errorData.message || `请求失败: ${response.status}`);
    }

    const text = await response.text();
    console.log('响应内容:', text);
    
    if (!text) {
      return { code: 500, message: '接口无返回内容', data: null as T };
    }
    
    const data = JSON.parse(text);
    console.log('解析后的数据:', JSON.stringify(data, null, 2));
    
    // 检查数据结构
    if (!data.hasOwnProperty('code') || !data.hasOwnProperty('data')) {
      console.error('响应数据结构不正确:', data);
      return { code: 500, message: '响应数据结构不正确', data: null as T };
    }
    
    return data;
  } catch (error) {
    console.error('API 请求错误:', error);
    return {
      code: 500,
      message: error instanceof Error ? error.message : '未知错误',
      data: null as T
    };
  }
}

// 客户相关 API
export const customerApi = {
  // 注册新客户
  register: (customer: Omit<Customer, 'customerID'>) => 
    request<void>('/customers/register', {
      method: 'POST',
      body: JSON.stringify(customer),
    }),
  
  // 客户登录
  login: (username: string, password: string) => 
    request<LoginResponse>('/customers/login', {
      method: 'POST',
      body: JSON.stringify({ username, password }),
    }),
  
  // 根据 ID 获取客户信息
  getById: (id: number) => 
    request<Customer>(`/customers/${id}`),
    
  // 获取当前登录的客户信息
  getCurrentUser: () => 
    request<Customer>('/customers'),
};

// 房间相关 API
export const roomApi = {
  // 获取所有房间
  getAll: () => 
    request<Room[]>('/rooms'),
  
  // 根据 ID 获取房间
  getById: (id: number) => 
    request<Room>(`/rooms/${id}`),
  
  // 创建新房间
  create: (room: Omit<Room, 'roomID'>) => 
    request<void>('/rooms', {
      method: 'POST',
      body: JSON.stringify(room),
    }),
  
  // 更新房间信息
  update: (id: number, room: Partial<Room>) => 
    request<void>(`/rooms/${id}`, {
      method: 'PUT',
      body: JSON.stringify(room),
    }),
  
  // 删除房间
  delete: (id: number) => 
    request<void>(`/rooms/${id}`, {
      method: 'DELETE',
    }),
  
  // 获取可用房间
  getAvailable: (roomType?: string) => {
    const query = roomType ? `?roomType=${encodeURIComponent(roomType)}` : '';
    return request<Room[]>(`/rooms/available${query}`);
  },
};

// 预订相关 API
export const bookingApi = {
  // 创建预订
  create: (booking: Omit<Booking, 'bookingID' | 'bookingTime' | 'customerID' | 'status'>) => 
    request<void>('/bookings', {
      method: 'POST',
      body: JSON.stringify(booking),
    }),
  
  // 获取所有预订
  getAll: () => 
    request<Booking[]>('/bookings'),
  
  // 根据 ID 获取预订
  getById: (id: number) => 
    request<Booking>(`/bookings/${id}`),
  
  // 根据客户 ID 获取预订
  getByCustomerId: () => 
    request<Booking[]>('/bookings/customer'),
  
  // 取消预订
  cancel: (id: number) => 
    request<void>(`/bookings/${id}`, {
      method: 'DELETE',
    }),
};

// 入住与退房相关 API
export const checkInApi = {
  // 办理入住
  checkIn: (bookingId: number) => 
    request<void>(`/checkin/${bookingId}/in`, {
      method: 'POST',
    }),
  
  // 办理退房
  checkOut: (bookingId: number) => 
    request<void>(`/checkin/${bookingId}/out`, {
      method: 'POST',
    }),
};

// 管理员相关 API
export const adminApi = {
  // 管理员登录
  login: (username: string, password: string) => 
    request<LoginResponse>('/admin/login', {
      method: 'POST',
      body: JSON.stringify({ username, password }),
    }),
    
  // 获取当前登录的管理员信息
  getCurrentUser: () => 
    request<Admin>('/admin/current'),
};